"use client"

import { View, Text, StyleSheet, TouchableOpacity, Modal, Pressable, Platform, ScrollView, Alert } from "react-native"
import { theme } from "../../constants/theme"
import { X, Volume2 } from "lucide-react-native"
import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming } from "react-native-reanimated"
import { useEffect, useState } from "react"
import { LinearGradient } from "expo-linear-gradient"

interface WordPart {
    text: string
    type: "前缀" | "词根" | "后缀"
    meaning: string
    etymology?: string
}

interface WordExample {
    word: string
    phonetic: string
    meaning: string
    explanation: string
    parts: WordPart[]
}

interface WordDetailSheetProps {
    visible: boolean
    onClose: () => void
    affix: string
    type: "prefix" | "suffix" | "root"
    examples: WordExample[]
}

export function WordDetailSheet({ visible, onClose, examples }: WordDetailSheetProps) {
    const translateY = useSharedValue(300)
    const [playingWord, setPlayingWord] = useState<string | null>(null)

    useEffect(() => {
        if (visible) {
            translateY.value = withSpring(0, {
                damping: 20,
                stiffness: 200,
            })
        } else {
            translateY.value = withTiming(300, {
                duration: 250,
            })
        }
    }, [visible])

    const animatedStyle = useAnimatedStyle(() => ({
        transform: [{ translateY: translateY.value }],
    }))

    const playAudio = (word: string) => {
        setPlayingWord(word)
        // Simulate audio playback
        Alert.alert("播放音频", `正在播放: "${word}"`)

        // Reset playing state after 2 seconds
        setTimeout(() => {
            setPlayingWord(null)
        }, 2000)
    }

    return (
        <Modal visible={visible} transparent animationType="none" onRequestClose={onClose}>
            <View style={styles.overlay}>
                <Pressable style={styles.backdrop} onPress={onClose} />
                <Animated.View style={[styles.content, animatedStyle]}>
                    {/* Handle bar */}
                    <View style={styles.header}>
                        <View style={styles.handle} />
                    </View>

                    {/* Close button */}
                    <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                        <X size={16} color={theme.colors.neutral.gray} />
                    </TouchableOpacity>

                    {/* Word list with buttons at the bottom of the content */}
                    <ScrollView
                        style={styles.scrollView}
                        showsVerticalScrollIndicator={false}
                        contentContainerStyle={styles.scrollContent}
                    >
                        {examples.map((example, index) => (
                            <View key={index} style={styles.wordCard}>
                                {/* Word header */}
                                <View style={styles.wordHeader}>
                                    <View style={styles.wordTitleRow}>
                                        <TouchableOpacity
                                            style={styles.wordTouchable}
                                            onPress={() => playAudio(example.word)}
                                            activeOpacity={0.7}
                                        >
                                            <Text style={styles.word}>
                                                {example.word.slice(0, -1)}
                                                <Text style={styles.highlight}>e</Text>
                                            </Text>
                                            <Volume2 size={14} color={theme.colors.neutral.gray} style={styles.volumeIcon} />
                                        </TouchableOpacity>
                                        <Text style={styles.phonetic}>{example.phonetic}</Text>
                                    </View>
                                    <Text style={styles.meaning}>{example.meaning}</Text>
                                </View>

                                {/* Word explanation */}
                                <Text style={styles.explanation}>
                                    <Text style={styles.wordInline}>{example.word}</Text>
                                    {example.explanation}
                                </Text>

                                {/* Word parts */}
                                <View style={styles.partsContainer}>
                                    <View style={styles.partsRow}>
                                        {example.parts.map((part, pIndex) => (
                                            <View key={pIndex} style={styles.partGroup}>
                                                <View style={styles.partBox}>
                                                    <Text style={styles.partLabel}>{part.type}</Text>
                                                    <Text style={styles.partText}>{part.text}</Text>
                                                    <Text style={styles.partMeaning}>{part.meaning}</Text>
                                                </View>
                                                {pIndex < example.parts.length - 1 && <Text style={styles.plusSign}>+</Text>}
                                            </View>
                                        ))}
                                    </View>

                                    {/* Etymology */}
                                    <View style={styles.etymologyContainer}>
                                        {example.parts.map(
                                            (part, pIndex) =>
                                                part.etymology && (
                                                    <Text key={pIndex} style={styles.etymology}>
                                                        <Text style={styles.etymologyLabel}>{part.text}</Text>
                                                        {`: ${part.etymology}`}
                                                    </Text>
                                                ),
                                        )}
                                    </View>
                                </View>
                            </View>
                        ))}

                        {/* Bottom buttons - now part of the scrollable content */}
                        <View style={styles.bottomButtons}>
                            <TouchableOpacity style={styles.secondaryButton} onPress={() => console.log("View more")}>
                                <Text style={styles.secondaryButtonText}>查看更多</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.primaryButton} onPress={() => console.log("Learn list")}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.gradientButton}
                                >
                                    <Text style={styles.primaryButtonText}>学习此列表</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>

                        {/* Add some bottom padding for iOS devices */}
                        <View style={{ height: Platform.OS === "ios" ? 24 : 12 }} />
                    </ScrollView>
                </Animated.View>
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        justifyContent: "flex-end",
    },
    backdrop: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "rgba(0, 0, 0, 0.3)",
    },
    content: {
        backgroundColor: theme.colors.neutral.white,
        borderTopLeftRadius: theme.borderRadius.large,
        borderTopRightRadius: theme.borderRadius.large,
        height: "80%",
        flexDirection: "column",
    },
    header: {
        alignItems: "center",
        paddingTop: theme.spacing.md,
        paddingBottom: theme.spacing.sm,
    },
    handle: {
        width: 36,
        height: 4,
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: 2,
    },
    closeButton: {
        position: "absolute",
        right: theme.spacing.lg,
        top: theme.spacing.md,
        width: 28,
        height: 28,
        borderRadius: 14,
        backgroundColor: theme.colors.neutral.lightGray,
        alignItems: "center",
        justifyContent: "center",
        zIndex: 10, // Ensure it's above other content
    },
    scrollView: {
        flex: 1,
    },
    scrollContent: {
        padding: theme.spacing.lg,
        paddingTop: theme.spacing.sm,
    },
    wordCard: {
        backgroundColor: theme.colors.neutral.background,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
    },
    wordHeader: {
        marginBottom: theme.spacing.md,
    },
    wordTitleRow: {
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.md,
        marginBottom: theme.spacing.xs,
    },
    wordTouchable: {
        flexDirection: "row",
        alignItems: "center",
    },
    word: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    volumeIcon: {
        marginLeft: theme.spacing.xs,
    },
    highlight: {
        color: theme.colors.primary.default,
    },
    phonetic: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontFamily: Platform.select({ ios: "System", android: "monospace" }),
    },
    meaning: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    explanation: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
        marginBottom: theme.spacing.md,
        lineHeight: 20,
    },
    wordInline: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    partsContainer: {
        gap: theme.spacing.md,
    },
    partsRow: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        flexWrap: "wrap",
        gap: theme.spacing.xs,
    },
    partGroup: {
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.xs,
    },
    partBox: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.sm,
        alignItems: "center",
        minWidth: 70,
    },
    partLabel: {
        fontSize: 10,
        color: theme.colors.neutral.gray,
        marginBottom: 1,
    },
    partText: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
        marginBottom: 2,
    },
    partMeaning: {
        fontSize: 10,
        color: theme.colors.neutral.darkGray,
    },
    plusSign: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
    },
    etymologyContainer: {
        gap: theme.spacing.xs,
    },
    etymology: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
        lineHeight: 18,
    },
    etymologyLabel: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    bottomButtons: {
        flexDirection: "row",
        padding: theme.spacing.md,
        gap: theme.spacing.md,
        marginTop: theme.spacing.md,
    },
    secondaryButton: {
        flex: 1,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.large,
        backgroundColor: theme.colors.neutral.lightGray,
        alignItems: "center",
    },
    secondaryButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.semiBold,
    },
    primaryButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
    },
    gradientButton: {
        paddingVertical: theme.spacing.sm,
        alignItems: "center",
    },
    primaryButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
})

